package com.neuedu.his.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.neuedu.his.po.Constantitem;
import com.neuedu.his.po.Register;
import com.neuedu.his.po.Checkapply;
import com.neuedu.his.po.Fmeditem;
import com.neuedu.his.po.Patientcosts;
import com.neuedu.his.service.ConstantitemService;
import com.neuedu.his.service.RegisterService;
import com.neuedu.his.service.CheckapplyService;
import com.neuedu.his.service.FmeditemService;
import com.neuedu.his.service.PatientcostsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/charge")
public class ChargeController {

    @Autowired private RegisterService registerService;
    @Autowired private CheckapplyService checkapplyService;
    @Autowired private FmeditemService fmeditemService;
    @Autowired private PatientcostsService patientcostsService;
    @Autowired private ConstantitemService constantItemService;

    /**
     * 收费方式列表（ConstantTypeID = 5）:contentReference[oaicite:0]{index=0}
     */
    @GetMapping("/feetype")
    public List<Map<String,Object>> getFeeTypes() {
        List<Constantitem> list = constantItemService.list(
                new LambdaQueryWrapper<Constantitem>()
                        .eq(Constantitem::getConstanttypeid, 5)
                        .eq(Constantitem::getDelmark,        1)
        );
        return list.stream().map(ci -> {
            Map<String,Object> m = new HashMap<>();
            m.put("id",   ci.getId());
            m.put("name", ci.getConstantname());
            return m;
        }).collect(Collectors.toList());
    }

    /**
     * 查询某病历号下所有已开立（state = 2）的项目
     */
    @GetMapping("/items")
    public Map<String,Object> getUnpaidItems(@RequestParam("medicalId") String medicalId) {
        Map<String,Object> resp = new HashMap<>();

        // 1) 查挂号记录
        Register reg = registerService.getOne(
                new LambdaQueryWrapper<Register>()
                        .eq(Register::getCasenumber, medicalId)
        );

        // 2) 若无此病历号，返回空结构
        if (reg == null) {
            resp.put("patient", Map.of("realname","", "idnumber","", "address",""));
            resp.put("items",   Collections.emptyList());
            return resp;
        }

        // 3) 填充患者信息
        resp.put("patient", Map.of(
                "realname", reg.getRealname(),
                "idnumber", reg.getIdnumber(),
                "address",  reg.getHomeaddress()
        ));

        // 4) 只查 state = 2（已开立）的 Checkapply
        List<Checkapply> list = checkapplyService.list(
                new LambdaQueryWrapper<Checkapply>()
                        .eq(Checkapply::getRegistid, reg.getId())
                        .eq(Checkapply::getState,    2)
        );

        // 5) 封装前端需要的 items
        List<Map<String,Object>> items = new ArrayList<>();
        for (Checkapply c : list) {
            Fmeditem f = fmeditemService.getById(c.getItemid());
            items.add(Map.of(
                    "id",           c.getId(),
                    "medicalid",    medicalId,
                    "name",         c.getName(),
                    "price",        f != null ? f.getPrice() : BigDecimal.ZERO,
                    "num",          c.getNum(),
                    "creationtime", c.getCreationtime(),
                    "state",        c.getState()
            ));
        }
        resp.put("items", items);
        return resp;
    }

    /**
     * 收费：前端传 itemIds 列表 + payType/paid/total/operatorId
     */
    @PostMapping("/pay")
    public ResponseEntity<String> pay(@RequestBody ChargeRequest req) {
        if (req.getItemIds() == null || req.getItemIds().isEmpty()) {
            return ResponseEntity.badRequest().body("未选择任何项目");
        }

        // 1) 插入每条收费记录到 Patientcosts
        for (Integer applyId : req.getItemIds()) {
            Checkapply c = checkapplyService.getById(applyId);
            Fmeditem  f = fmeditemService.getById(c.getItemid());

            Patientcosts pc = new Patientcosts();
            pc.setRegistid(c.getRegistid());
            pc.setInvoiceid(0);                     // 发票模块后续补充
            pc.setItemid(c.getItemid());
            pc.setItemtype(c.getRecordtype());
            pc.setName(c.getName());
            pc.setPrice(f != null ? f.getPrice() : BigDecimal.ZERO);
            pc.setAmount(BigDecimal.valueOf(c.getNum()));
            pc.setDeptid(f != null ? f.getDeptid() : null);
            pc.setCreatetime(c.getCreationtime());
            pc.setCreateoperid(c.getDoctorid());
            pc.setPaytime(new Date());
            pc.setRegisterid(req.getOperatorId());
            pc.setFeetype(req.getPayType());
            pc.setBackid(null);
            patientcostsService.save(pc);
        }

        // 2) 更新所有已开立项目状态 → 已收费（4）
        checkapplyService.update(
                new LambdaUpdateWrapper<Checkapply>()
                        .in(Checkapply::getId, req.getItemIds())
                        .set(Checkapply::getState, 4)
        );

        return ResponseEntity.ok("ok");
    }

    /** 前端请求体映射 */
    public static class ChargeRequest {
        private List<Integer> itemIds;
        private Integer       payType;
        private BigDecimal    paid;
        private BigDecimal    total;
        private Integer       operatorId;

        public List<Integer> getItemIds()                { return itemIds; }
        public void          setItemIds(List<Integer> i) { this.itemIds = i; }
        public Integer       getPayType()                { return payType; }
        public void          setPayType(Integer p)       { this.payType = p; }
        public BigDecimal    getPaid()                   { return paid; }
        public void          setPaid(BigDecimal p)       { this.paid = p; }
        public BigDecimal    getTotal()                  { return total; }
        public void          setTotal(BigDecimal t)      { this.total = t; }
        public Integer       getOperatorId()             { return operatorId; }
        public void          setOperatorId(Integer o)    { this.operatorId = o; }
    }
}
